package com.lagou.handler;

import com.lagou.ServerBootstrap;
import com.lagou.pojo.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.internal.ReflectionUtil;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @author 陶肖寅
 * @version V1.0
 * @Package handler
 * @email fromlx@126.com
 * @date 2020-03-23 22:00
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 */
public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //对接受到的请求信息做处理
        //判断是否符合约定，符合则调用本地方法，返回数据
        //msg:UserService#sayHello#are you ok?
        RpcRequest request = (RpcRequest) msg;
       Class clzz =  Class.forName(request.getClassName());
        //从Spring容器中获取目标类
        Object targetService = ServerBootstrap.applicationContext.getBean(clzz);
        //反射获取到method方法
        Method method = targetService.getClass().getMethod(request.getMethodName(),request.getParameterTypes());
        //执行方法
        Object result = method.invoke(targetService,request.getParameters());
        //将返回结果写入通道中
        ctx.writeAndFlush(result);

//        if(msg.toString().startsWith("UserService")){
//            UserServerImpl userServer = new UserServerImpl();
//            String result = userServer.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
//            ctx.writeAndFlush(result);
//        }
    }
}
